// 该文件专门用于创建整个应用的路由器
import Vue from "vue";
import VueRouter from "vue-router";
import About from "../pages/About";
import Home from "../pages/Home";
import News from "../pages/News";
import Message from "../pages/Message";
import Detail from "../pages/Detail";

Vue.use(VueRouter);

// 创建并暴露一个路由器
const router = new VueRouter({
  routes: [
    {
      name: "about",
      path: "/about",
      component: About,
      meta: {
        title: "关于",
      },
    },
    {
      name: "home",
      path: "/home",
      component: Home,
      meta: {
        title: "主页",
      },
      children: [
        {
          name: "news",
          path: "news",
          component: News,
          // 路由元信息
          meta: {
            title: "新闻",
            isAuth: true,
          },
        },
        {
          name: "message",
          path: "message",
          component: Message,
          meta: {
            title: "消息",
            isAuth: true,
          },
          children: [
            {
              name: "detail",
              path: "detail",
              // path: 'detail/:id/:title',
              component: Detail,
              meta: {
                title: "详情",
              },
              // props 的第一种写法。值为对象，
              /* props: {
                a: 1,
                b: "hello",
              }, */

              // props 的第二种写法。值为布尔值，
              // props: true,

              // props 的第三种写法。值为函数，
              /* props($route) {
                return {
                  id: $route.query.id,
                  title: $route.query.title,
                };
              }, */
              props({ query: { id, title } }) {
                return {
                  id,
                  title,
                  a: 1,
                  b: "hello",
                };
              },
            },
          ],
        },
      ],
    },
  ],
});

// 全局前置路由守卫 —— 初始化的时候被调用、每次路由之间切换之前被调用
router.beforeEach((to, from, next) => {
  console.log("前", to, from);
  if (to.meta.isAuth) {
    // 判断是否需要鉴权
    if (localStorage.getItem("school") === "atguigu") {
      // 手动一下
      // document.title = to.meta.title || 'vue-test';
      next();
    } else {
      alert("学校名不对，无权限查看");
    }
  } else {
    // document.title = to.meta.title || 'vue-test';
    next();
  }
});

// 全局后置路由守卫 —— 初始化的时候被调用、每次路由之间切换之后被调用
router.afterEach((to, from) => {
  console.log("后", to, from);
  document.title = to.meta.title || "vue-test";
});

export default router;
